<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="归属部门" prop="deptId" v-if="this.$store.state.user.roles.indexOf('admin')!=-1 || this.$store.state.user.roles.indexOf('chairman')!=-1">
        <treeselect v-model="queryParams.deptId" :options="enabledDeptOptions" :show-count="true" placeholder="请选择归属部门" style="width: 215px;"/>
      </el-form-item>
      <el-form-item label="用户姓名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户性别" prop="sex">
        <el-select v-model="queryParams.sex" placeholder="请选择用户性别" clearable>
          <el-option
            v-for="dict in dict.type.sys_user_sex"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建日期">
              <el-date-picker
                v-model="daterangeDateTime"
                style="width: 240px"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:userInfo:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:userInfo:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:userInfo:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:userInfo:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
      <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
    </el-row>

    <el-table v-loading="loading" :data="userInfoList" :summary-method="getSummaries"
    show-summary @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="56" align="center" />
      <!-- <el-table-column label="" align="center" prop="id" /> -->
      <el-table-column label="序号" type="index" width="100" align="center">
        <template slot-scope="scope">
          {{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}
        </template>
      </el-table-column>
      <el-table-column label="用户编号" align="center" prop="id" v-if="columns[0].visible"/>
      <el-table-column label="用户姓名" align="center" prop="userName" v-if="columns[1].visible" :show-overflow-tooltip="true"/>
      <el-table-column label="用户性别" align="center" prop="sex" v-if="columns[2].visible">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:userInfo:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:userInfo:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      :pageSizes="queryParams.pageSizes"
      @pagination="getList"
    />

    <!-- 添加或修改用户信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" :close-on-click-modal="false" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户姓名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户姓名" />
        </el-form-item>
        <el-form-item label="用户性别" prop="sex">
          <el-select v-model="form.sex" placeholder="请选择用户性别">
            <el-option
              v-for="dict in dict.type.sys_user_sex"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUserInfo, getUserInfo, delUserInfo, addUserInfo, updateUserInfo, deptTreeSelect} from "@/api/userInfo/userInfo";
import { Decimal } from 'decimal.js';
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "UserInfo",
  dicts: ['sys_user_sex'],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户信息表格数据
      userInfoList: [],
      // 弹出层标题
      title: "",
      // 所有部门树选项
      deptOptions:  [],
      // 过滤掉已禁用部门树选项
      enabledDeptOptions:  [],
      // 是否显示弹出层
      open: false,
      // 年月日时间范围
      daterangeDateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: null,
        sex: null,
        deptId: null,
        pageSizes: [10, 20, 30, 50,100,200,300,500],
      },
      // 表单参数
      form: {},
      // 列信息
      columns: [
        { key: 0, label: `用户编号`, visible: true },
        { key: 1, label: `用户名称`, visible: true },
        { key: 2, label: `用户性别`, visible: true },
      ],
      // 表单校验
      rules: {
        userName: [
          { required: true, message: "用户姓名不能为空", trigger: "change" }
        ],
        sex: [
          { required: true, message: "用户性别不能为空", trigger: "change" }
        ],
        delFlag: [
          { required: true, message: "删除标志不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    console.log(this.$store.state.user.roles)
    if(this.$store.state.user.roles.indexOf("chairman") != -1||this.$store.state.user.roles.indexOf("admin") != -1){
      this.getDeptTree();
    }
  },
  methods: {
  getSummaries(param) {
      const { columns, data } = param;
      const sums = {};
      columns.forEach((column, index) => {
          if (index === 0) {
              sums[index] = '合计';
              return;
          }
          const values = data.map(item => Number(item[column.property]));
          if (column.label == "用户编号") {
            if (!values.every(value => isNaN(value))) {
                sums[index] = values.reduce((prev, curr) => {
                    const value = Number(curr);
                    if (!isNaN(value)) {
                        return prev + curr;
                    } else {
                        return prev;
                    }
                }, 0);
                 //sums[index] += ' kg';
                 const decimalNumber = new Decimal(sums[index]);
                 // 使用toFixed，传入0作为小数位数，实现银行家舍入
                 const roundedNumber = decimalNumber.toFixed(2, Decimal.ROUND_HALF_EVEN);
                 sums[index] = roundedNumber;
            } else {
                 sums[index] = 'N/A';
            }
          }
      });
      return sums;
   },
   /** 查询部门下拉树结构 */
   getDeptTree() {
     deptTreeSelect().then(response => {
       this.deptOptions = response.data;
       this.enabledDeptOptions = this.filterDisabledDept(JSON.parse(JSON.stringify(response.data)));
     });
   },
   // 过滤禁用的部门
   filterDisabledDept(deptList) {
     return deptList.filter(dept => {
       if (dept.disabled) {
         return false;
       }
       if (dept.children && dept.children.length) {
         dept.children = this.filterDisabledDept(dept.children);
       }
       return true;
     });
   },
   // 筛选节点
   filterNode(value, data) {
     if (!value) return true;
     return data.label.indexOf(value) !== -1;
   },
   // 节点单击事件
   handleNodeClick(data) {
     this.queryParams.deptId = data.id;
     this.handleQuery();
   },
    /** 查询用户信息列表 */
    getList() {
        this.loading = true;
        this.queryParams.params = {};
        if (null != this.daterangeDateTime && '' != this.daterangeDateTime) {
          this.queryParams.params["beginDateTime"] = this.daterangeDateTime[0];
          this.queryParams.params["endDateTime"] = this.daterangeDateTime[1];
        }else{
          var now = new Date();
          var year = now.getFullYear();
          var month = now.getMonth();
          var date = now.getDate();
          month = month + 1;
          month = month.toString().padStart(2, '0');
          date = date.toString().padStart(2, '0');
          var defaultDate = `${year}-${month}-${date}`;
          this.daterangeDateTime = [];
          this.daterangeDateTime[0] = defaultDate;
          this.daterangeDateTime[1] = defaultDate;
          this.queryParams.params["beginDateTime"] = defaultDate;
          this.queryParams.params["endDateTime"] = defaultDate;
      }
      listUserInfo(this.queryParams).then(response => {
        this.userInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userName: null,
        sex: null,
        delFlag: null,
        userId: null,
        deptId: null,
        dateTime: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeDateTime = [];
      this.queryParams.deptId = null;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getUserInfo(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改用户信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateUserInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUserInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除用户信息编号为"' + ids + '"的数据项？').then(function() {
        return delUserInfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/userInfo/export', {
        ...this.queryParams
      }, `userInfo_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
  /* /deep/ 为深度操作符，可以穿透到子组件 */
  /deep/ .el-table {
    display: flex;
    flex-direction: column;
  }

  /* order默认值为0，只需将表体order置为1即可移到最后，这样合计行就上移到表体上方 */
  /deep/ .el-table__body-wrapper {
    order: 0;
  }
</style>
